#include "mytp.h"
#include <QDebug>
#include <QStringList>
// void WorkerThread::run(){
//          QString result;
//          /* ... here is the expensive or blocking operation ... */
//          emit resultReady(result);
// }

void MyTp::startWorkInAThread()
{
//      WorkerThread *workerThread = new WorkerThread(this);
//      connect(workerThread, &WorkerThread::resultReady, this, &MyTp::handleResults);
//      connect(workerThread, &WorkerThread::finished, workerThread, &MyTp::deleteLater);
//      workerThread->start();
}

MyTp::MyTp() 
{
    this->begin=false;
    this->isOpen=false;
    this->pmyport=NULL;
    this->old_value=-99999;
}
void MyTp::open(){
    if(this->pmyport!=NULL) delete this->pmyport;
    pmyport=new QSerialPort();
    pmyport->setPortName("COM1");
    pmyport->setBaudRate(QSerialPort::Baud1200);
    pmyport->setDataBits(QSerialPort::Data7);
    pmyport->setParity(QSerialPort::OddParity);
    pmyport->setStopBits(QSerialPort::OneStop);
    pmyport->setFlowControl(QSerialPort::NoFlowControl);
    if (pmyport->open(QIODevice::ReadWrite)) {
        qDebug()<<"open";
        this->isOpen=true;
        QObject::connect(pmyport,SIGNAL(readyRead()), this, SLOT(onReady()));
    }else{
        this->isOpen=false;
    }
}
void MyTp::parse(QString str)
{
    QString str1;
    str1.append(this->last);
    str1.append(str);
    QStringList list1 = str1.split(QLatin1Char('\r'));
    if(this->begin){
        for (int i = 0; i < list1.size()-1; ++i){
            str_list.append(list1.at(i));
        }
        this->last=list1.at(list1.size()-1);
    }else{
        if (list1.size()>1){
            this->begin=true;    
            for (int i = 1; i < list1.size()-1; ++i){
                str_list.append(list1.at(i));
            }
            this->last=list1.at(list1.size()-1);
        }
    }
    if (str_list.size()>10){
        str_list.removeFirst();
    }
    double l=read();
    emit dataArrive(l);
}
void MyTp::onReady()
{
    // qDebug()<<"ready";
    const QByteArray data = pmyport->readAll();
    if(data.length()>0) {
        QString str1(data);
        this->parse(str1);
    }else{
        qDebug()<<"data len <=0";
    }

}
double MyTp::read()
{
    if(str_list.size()<1) return -99999999;
    QString msg=str_list.at(str_list.size()-1);
    qDebug()<<msg;
    // QString msg;
    // char buff[1024];
    // qint64 nread;
    // if (!pmyport->isOpen())
    // {
    //     return 0;
    // }
    // nread=pmyport->readLine(buff,1024);
    // if (nread == -1)
    //     return 0;
    // nread=pmyport->readLine(buff,1024);
    // if (nread != -1)
    //     buff[nread] = '\0';
    // else
    //     return 0;
    // msg.clear();
    // msg.append(buff);
    // qDebug()<<msg;
    msg=msg.mid(2,9);
    qDebug()<<msg;
    return msg.toDouble();
}
MyTp::~MyTp()
{
    // pmyport->close();
    // delete pmyport;
}
